package com.xxx.video.mine.activitys;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.utils.FontCacheUtils;
import com.xxx.video.commen.utils.StatusBarUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.utils.SystemActivityUtils;
import com.xxx.video.commen.utils.ToastUtils;
import com.xxx.video.commen.utils.UriUtils;
import com.xxx.video.commen.views.FontTextView;
import com.xxx.video.mine.presenters.AddVideoPresenter;
import com.xxx.video.mine.presenters.IAddVideoView;

import butterknife.BindView;
import butterknife.OnClick;

public class AddVideoActivity extends BaseActivity<AddVideoPresenter> implements IAddVideoView {
    /**
     * start album activity
     */
    public static final int START_ALBUM_ACTIVITY = 202;
    /**
     * start video album activity
     */
    public static final int START_ALBUM_VIDEO_ACTIVITY = 203;
    /**
     * request permission code
     */
    public static final int REQUEST_VIDEO_PERMISSION_CODE = 204;
    /**
     * request permission code
     */
    public static final int REQUEST_IMAGE_PERMISSION_CODE = 205;

    @BindView(R.id.tv_add_video_activity_video_title)
    TextView tvAddVideoActivityVideoTitle;
    @BindView(R.id.et_add_video_activity_video_title)
    EditText etAddVideoActivityVideoTitle;
    @BindView(R.id.tv_add_video_activity_add_video_title)
    TextView tvAddVideoActivityAddVideoTitle;
    @BindView(R.id.iv_add_video_activity_add_video)
    ImageView ivAddVideoActivityAddVideo;
    @BindView(R.id.tv_add_video_activity_add_video_cover_title)
    TextView tvAddVideoActivityAddVideoCoverTitle;
    @BindView(R.id.iv_add_video_activity_add_video_cover)
    ImageView ivAddVideoActivityAddVideoCover;
    @BindView(R.id.tv_add_video_activity_add_video_submit)
    TextView tvAddVideoActivityAddVideoSubmit;

    private String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    /**
     * video path
     */
    private String videoPath;
    /**
     * video cover path
     */
    private String videoCoverPath;
    /**
     * video Duration
     */
    private long mVideoDuration;

    @Override
    public void initToolbarData() {
        super.initToolbarData();
        showActionBar();
        StatusBarUtil.getInstance().setStatusBarTransparent(this, true);
        setIsShowActionbarLine(true);
        setActionBarTitle(R.string.title_add_video_activity);
        Typeface customFont = FontCacheUtils.getInstance().getTypeface(FontTextView.ttf3, this);
        etAddVideoActivityVideoTitle.setTypeface(customFont);
    }

    @Override
    protected AddVideoPresenter createPresenter() {
        return new AddVideoPresenter(this, this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_add_video;
    }

    @Override
    public void initData(Bundle extras) {
        showLayoutStatus(1);
    }

    @OnClick({R.id.iv_add_video_activity_add_video, R.id.iv_add_video_activity_add_video_cover, R.id.tv_add_video_activity_add_video_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add_video_activity_add_video:
                startCheckVideoActivity();
                break;
            case R.id.iv_add_video_activity_add_video_cover:
                showCheckImageDialog();
                break;
            case R.id.tv_add_video_activity_add_video_submit:
                getPresenter().submit(mVideoDuration);
                break;
            default:
                break;
        }
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @Override
    public void startCheckVideoActivity() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            /*
             * have permission
             */
            SystemActivityUtils.getInstance().startAlbumVideoActivity(this, START_ALBUM_VIDEO_ACTIVITY);
        } else {
            /*
             * no permission
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // You can directly ask for the permission.
                requestPermissions(permissions, REQUEST_VIDEO_PERMISSION_CODE);
            } else {
                // please open read external storage permission
                ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_read_and_write_external_storage_permission));
            }
        }
    }

    @Override
    public void showCheckImageDialog() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            /*
             * have permission
             */
            SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
        } else {
            /*
             * no permission
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // You can directly ask for the permission.
                requestPermissions(permissions, REQUEST_IMAGE_PERMISSION_CODE);
            } else {
                // please open read external storage permission
                ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_read_and_write_external_storage_permission));
            }
        }
    }

    @Override
    public String getVideoPath() {
        return videoPath;
    }

    @Override
    public String getVideoCoverPath() {
        return videoCoverPath;
    }

    @Override
    public String getVideoTitle() {
        return etAddVideoActivityVideoTitle.getText().toString().trim();
    }

    @Override
    public void releaseSuccess() {
        ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_add_video_success));
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == START_ALBUM_ACTIVITY) {
                    Uri imageUri = data.getData();
                    videoCoverPath = UriUtils.getInstance().getRealPathFromURI(this, imageUri);
                    Glide.with(this).load(imageUri).apply(new RequestOptions().centerCrop()).into(ivAddVideoActivityAddVideoCover);
                } else if (requestCode == START_ALBUM_VIDEO_ACTIVITY) {
                    Uri videoUri = data.getData();
                    videoPath = UriUtils.getInstance().getVideoRealPathFromURI(this, videoUri);
                    //ms
//                    mVideoDuration = UriUtils.getInstance().getVideoDurationFromURI(this, videoUri);
                    try {
                        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                        retriever.setDataSource(videoPath);
                        String timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                        mVideoDuration = Long.valueOf(timeString);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Glide.with(this).load(videoPath).apply(new RequestOptions().centerCrop()).into(ivAddVideoActivityAddVideo);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_VIDEO_PERMISSION_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission is granted. Continue the action or workflow
                    // in your app.
                    SystemActivityUtils.getInstance().startAlbumVideoActivity(this, START_ALBUM_VIDEO_ACTIVITY);
                } else {
                    // Explain to the user that the feature is unavailable because
                    // the features requires a permission that the user has denied.
                    // At the same time, respect the user's decision. Don't link to
                    // system settings in an effort to convince the user to change
                    // their decision.
                    ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_read_and_write_external_storage_permission));
                }
                return;
            case REQUEST_IMAGE_PERMISSION_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission is granted. Continue the action or workflow
                    // in your app.
                    SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
                } else {
                    // Explain to the user that the feature is unavailable because
                    // the features requires a permission that the user has denied.
                    // At the same time, respect the user's decision. Don't link to
                    // system settings in an effort to convince the user to change
                    // their decision.
                    ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_read_and_write_external_storage_permission));
                }
                return;
            default:
                break;
        }
    }

}
